import { defineStore } from 'pinia';
import { ref } from 'vue';
import { getAccountList } from '@/api/index';

/**
 * 账本状态管理
 */
export const useAccountStore = defineStore('account', () => {
  // 当前选中的账本
  const currentAccount = ref(null);
  
  // 账本列表
  const accountList = ref([]);
  
  // 是否已加载账本列表
  const isLoaded = ref(false);

  /**
   * 设置当前账本
   */
  const setCurrentAccount = (account) => {
    currentAccount.value = account;
    // 保存到本地存储
    if (account) {
      localStorage.setItem('currentAccount', JSON.stringify(account));
    } else {
      localStorage.removeItem('currentAccount');
    }
  };

  /**
   * 从本地存储恢复当前账本
   */
  const restoreCurrentAccount = () => {
    const savedAccount = localStorage.getItem('currentAccount');
    if (savedAccount) {
      try {
        currentAccount.value = JSON.parse(savedAccount);
      } catch (error) {
        console.error('恢复账本信息失败:', error);
        localStorage.removeItem('currentAccount');
      }
    }
  };

  /**
   * 加载账本列表
   */
  const loadAccountList = async () => {
    try {
      const response = await getAccountList();
      console.log('Store加载账本列表响应:', response);
      
      // 响应拦截器已经提取了 data，直接使用即可
      if (Array.isArray(response)) {
        accountList.value = response;
        isLoaded.value = true;
        
        console.log('Store账本列表加载成功:', accountList.value.length, '个账本');
        
        // 如果没有选中的账本，自动选择第一个
        if (!currentAccount.value && accountList.value.length > 0) {
          setCurrentAccount(accountList.value[0]);
          console.log('自动选择第一个账本:', accountList.value[0].remark);
        }
        
        // 如果当前账本已被删除，清除选择
        if (currentAccount.value) {
          const exists = accountList.value.find(a => a.id === currentAccount.value.id);
          if (!exists) {
            console.log('当前账本已被删除，重新选择');
            setCurrentAccount(accountList.value.length > 0 ? accountList.value[0] : null);
          }
        }
        
        return accountList.value;
      } else {
        console.error('账本列表响应格式错误:', response);
        accountList.value = [];
        isLoaded.value = true;
        return [];
      }
    } catch (error) {
      console.error('加载账本列表失败:', error);
      accountList.value = [];
      isLoaded.value = true;
      return [];
    }
  };

  /**
   * 清空账本信息（用户退出登录时调用）
   */
  const clearAccount = () => {
    currentAccount.value = null;
    accountList.value = [];
    isLoaded.value = false;
    localStorage.removeItem('currentAccount');
  };

  /**
   * 刷新账本列表
   */
  const refreshAccountList = () => {
    isLoaded.value = false;
    return loadAccountList();
  };

  return {
    currentAccount,
    accountList,
    isLoaded,
    setCurrentAccount,
    restoreCurrentAccount,
    loadAccountList,
    clearAccount,
    refreshAccountList
  };
});


